<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket</title>
</head>

<body>
    <p>
        <button onclick="openSocket()">WebSocket连接</button>
        <button onclick="sendMessage()">WebSocket发送消息</button>
        <button onclick="closeSocket()">WebSocket关闭</button>
    </p>
    <div id="message">

    </div>
</body>

<script>
    let ws = null;
    let countMessage = 0;
    const msg = document.getElementById('message');
    const showGreeting = (message) => {
        const p = document.createElement('p');
        p.appendChild(document.createTextNode(message));
        msg.appendChild(p);
    }

    const openSocket = message => {
        ws = new WebSocket('ws://localhost:7000/ws1/1233');
        ws.onopen = () => {
            countMessage = 0;
            showGreeting('onopen: 连接开启。');
        }

        ws.onmessage = (event) => {
            showGreeting('onmessage: ' + event.data);
        }

        ws.onclose = () => {
            countMessage = 0;
            msg.innerHTML = '';
            ws = null;
            showGreeting('onclose: 连接关闭。');
        }

        ws.onerror = (error) => {
            console.log('error: ', error);
            countMessage = 0;
        }
    }

    const sendMessage = () => {
        ws ? showGreeting(`这是客户端的消息: ${countMessage}`) : '';
        ws?.send(`这是客户端的消息: ${countMessage++}`);

    }

    const closeSocket = () => {
        ws?.close();
    }


</script>

</html>